﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using Ares.Engine.Lib;
using ExtensionManager;

namespace Ares.Engine
{
    public class ExtensionLoader
    {
        public ExtensionManager<IPlugin, IHost> manager = new ExtensionManager<IPlugin, IHost>();

        public IHost host;

        public ExtensionLoader()
        {
            //Listen to the events
            manager.AssemblyFailedLoading += new ExtensionManager<IPlugin, IHost>.AssemblyFailedLoadingEventHandler(manager_AssemblyFailedLoading);
            manager.AssemblyLoaded += new ExtensionManager<IPlugin, IHost>.AssemblyLoadedEventHandler(manager_AssemblyLoaded);
            manager.AssemblyLoading += new ExtensionManager<IPlugin, IHost>.AssemblyLoadingEventHandler(manager_AssemblyLoading);

            //Loads .cs, .vb, .js, and .dll extensions
            manager.LoadDefaultFileExtensions();

            //We need to add our library with the interfaces to the list
            manager.SourceFileReferencedAssemblies.Add("Backup.Engine.Lib.dll");


        }

        public List<IBackUpStorage> LoadStorageExtensions(string dir)
        {
            List<IBackUpStorage> ReStorages = new List<IBackUpStorage>();

            //Lookin in the AppPath\Extensions\ folder
            manager.LoadExtensions(dir);

            //Loop through all the extensions
            foreach (Extension<IPlugin> extOn in manager.Extensions)
            {
                //It needs to know we're the host!
                extOn.Instance.Host = host;

                //Call the Init-Routine
                

                //Load database implementations
                var BackupStorages = extOn.InstanceAssembly.GetTypes().Where(p => typeof(IBackUpStorage).IsAssignableFrom(p) && p.IsClass);

                foreach (Type db in BackupStorages)
                {
                    IBackUpStorage BackupStorage = (IBackUpStorage)Activator.CreateInstance(db);

                    if (BackupStorage != null)
                    {
                        BackupStorage.host = host;
                        ReStorages.Add(BackupStorage);
                    }
                }
            }

            return ReStorages;
        }

        void manager_AssemblyLoading(object sender, AssemblyLoadingEventArgs e)
        {

        }

        void manager_AssemblyLoaded(object sender, AssemblyLoadedEventArgs e)
        {

        }

        void manager_AssemblyFailedLoading(object sender, AssemblyFailedLoadingEventArgs e)
        {

        }
    }
}
